package Solutions;

/**
 * @Classname OneEditAway
 * @Description TODO
 * @Date 2021/6/13 15:02
 * @Created by LengDanran
 * 字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。
 * 给定两个字符串，编写一个函数判定它们是否只需要一次(或者零次)编辑。
 *
 * 示例 1:
 *
 * 输入:
 * first = "pale"
 * second = "ple"
 * 输出: True
 *
 *
 *
 * 示例 2:
 *
 * 输入:
 * first = "pales"
 * second = "pal"
 * 输出: False
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/one-away-lcci
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class OneEditAway {

    /***
     * 执行结果：
     * 通过
     * 显示详情
     *
     * 执行用时：2 ms, 在所有 Java 提交中击败了97.52% 的用户
     * 内存消耗：38.4 MB, 在所有 Java 提交中击败了56.86% 的用户
     */
    public boolean oneEditAway(String first, String second) {
        if (first.equals(second)) return true;
        int firstLength = first.length();
        int secondLength = second.length();
        if (firstLength - secondLength < -1 || firstLength - secondLength > 1) return false;
        int tmp;
        String tmpStr;
        if (firstLength < secondLength) {
            tmp = firstLength;
            firstLength = secondLength;
            secondLength = tmp;
            tmpStr = first;
            first = second;
            second = tmpStr;
        }
        if (firstLength == secondLength) {
            int count = 0;
            for (int i = 0; i < firstLength; i++) {
                if (first.charAt(i) != second.charAt(i)) count++;
                if (count > 1) return false;
            }
        } else {
            int count = 0;
            for (int i = 0, j = 0; i < firstLength && j <secondLength; i++ ,j++) {
                if (first.charAt(i) != second.charAt(j)) {
                    j--;
                    count++;
                    if (count > 1) return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(new OneEditAway().oneEditAway("ple", "plea"));

    }
}
